package com.jielihaofeng.chat.localcache.impl;

import com.jielihaofeng.chat.constants.LocalCacheType;
import com.jielihaofeng.chat.localcache.AbstractTimedRefreshLocalCache;
import com.jielihaofeng.framework.common.entity.BaseEntity;
import com.jielihaofeng.system.convert.SysUserConvert;
import com.jielihaofeng.system.entity.SysUserLocalCacheEntity;
import com.jielihaofeng.system.entity.SysUserEntity;
import com.jielihaofeng.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description: 用户管理本地缓存
 *
 * @author xieli
 * @version 1.0
 * @date 2022/10/3 5:43 PM
 * @since JDK 1.8
 */
@Slf4j
public class SysUserLocalCache extends AbstractTimedRefreshLocalCache<Long, SysUserLocalCacheEntity> {

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected SysUserLocalCacheEntity loadFromDB(Long userId) {
        SysUserEntity sysUserEntity = sysUserService.getById(userId);
        return SysUserConvert.INSTANCE.convert2LocalCacheEntity(sysUserEntity);
    }

    @Override
    protected Map<Long, SysUserLocalCacheEntity> loadAllFromDB(List<Long> keys) {
        List<SysUserEntity> sysUsers = sysUserService.listByIds(keys);
        if (CollectionUtils.isEmpty(sysUsers)) {
            return new HashMap<>();
        }
        return sysUsers.stream().collect(Collectors.toMap(BaseEntity::getId, SysUserConvert.INSTANCE::convert2LocalCacheEntity, (v2, v1) -> v2));
    }

    @Override
    protected Map<Long, SysUserLocalCacheEntity> loadAll() {
        List<SysUserEntity> sysUsers = sysUserService.list();
        if (CollectionUtils.isEmpty(sysUsers)) {
            return new HashMap<>();
        }
        return sysUsers.stream().collect(Collectors.toMap(BaseEntity::getId, SysUserConvert.INSTANCE::convert2LocalCacheEntity, (v2, v1) -> v2));
    }

    @Override
    protected boolean isLoadAll() {
        return true;
    }

    @Override
    protected long maximumSize() {
        return 1000;
    }

    @Override
    protected long refreshPeriodMinutes() {
        return 60 * 24;
    }

    @Override
    public String cacheType() {
        return LocalCacheType.SYS_USER.name();
    }
}
